package br.com.android.financas.fragments;

import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.android.financas.DiaBase;
import br.com.android.financas.R;
import br.com.android.financas.activities.HomePoupanca;
import br.com.android.financas.adapter.DiaBaseAdapter;
import br.com.android.financas.adapter.PoupancaListaAdapter;
import br.com.android.financas.model.Poupanca;
import br.com.android.financas.repositorio.RepositorioPoupanca;
import br.com.android.financas.repositorio.impl.RepositorioPoupancaImpl;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.ActionMode;

public class ListaPoupanca extends SherlockFragment {

	private RepositorioPoupanca repositorioPoupanca;
	private ListView lista;
	private ListView listaBases;
	private PoupancaListaAdapter adapter;
	private DiaBaseAdapter adapterDias;
	private List<Poupanca> poupancas;
	private List<DiaBase> diasBases;
	private View footer;
	private ActionMode mMode;
	private boolean changed;
	private Intent intent;
	private Poupanca poupanca;
	private OnChangeListener mListener;
	private View selecionado;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		loadRepositorios(getActivity());

		lista = (ListView) getView().findViewById(R.listaPoupanca.lista);
		footer = View
				.inflate(getActivity(), R.layout.poupanca_item_total, null);
		View header = View.inflate(getActivity(),
				R.layout.poupanca_lista_header, null);
		lista.addFooterView(footer);
		lista.addHeaderView(header);

		listaBases = (ListView) getView().findViewById(
				R.listaPoupanca.listaDiasBases);
		View headerBase = View.inflate(getActivity(),
				R.layout.datas_bases_header, null);

		listaBases.addHeaderView(headerBase);

		lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> adapterView, View view,
					int i, long l) {

				if(selecionado!=null){
					limparSelecionado();
					mMode.finish();
					return ;
				}

				poupanca = (Poupanca) lista.getAdapter().getItem(i);

				intent = new Intent(getActivity(), HomePoupanca.class);
				intent.putExtra("id", (Integer) poupanca.getId());
				startActivityForResult(intent, 1);

				// HomePoupanca.callMe(ListaPoupanca.this.getActivity(),poupanca.getId());
			}
		});

		lista.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view,
					int i, long l) {

				limparSelecionado();
				selecionado=view;
				view.setBackgroundResource(android.R.color.holo_blue_light);


				poupanca = (Poupanca) lista.getAdapter().getItem(i);

				mMode = getSherlockActivity().startActionMode(
						new AnActionModeOfEpicProportions());
				return true;
			}
		});

	}

	private void limparSelecionado(){
		if(selecionado!=null){
			selecionado.setBackgroundResource(android.R.color.transparent);

		}
		selecionado=null;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.lista_poupanca, container, false);

		return view.findViewById(R.listaPoupanca.layout);
	}

	@Override
	public void onResume() {
		super.onResume();
		//if (changed || poupancas == null)
			loadData();
	}

	public void loadRepositorios(Activity activity) {
		try {
			repositorioPoupanca = new RepositorioPoupancaImpl(activity);
		} catch (SQLException e) {
		}
	}

	public List<Poupanca> getPoupancas() {
		if (poupancas == null || changed)
			poupancas=repositorioPoupanca.listar();
		return poupancas;
	}

	public List<DiaBase> getDiasBases() {
		if (diasBases == null || changed){
			diasBases = repositorioPoupanca.getDiasBases();
			Collections.sort(diasBases);
		}
		return diasBases;
	}

	public void loadData() {

		adapter = new PoupancaListaAdapter(getActivity(),
				R.layout.poupanca_item, getPoupancas());
		lista.setAdapter(adapter);

		TextView total = (TextView) footer
				.findViewById(R.listaItemPoupanca.total);
		total.setText(NumberFormat.getCurrencyInstance().format(
				repositorioPoupanca.getTotal()));

		adapterDias = new DiaBaseAdapter(getActivity(), R.layout.poupanca_item,
				getDiasBases());
		listaBases.setAdapter(adapterDias);
	}

	private final class AnActionModeOfEpicProportions implements
			ActionMode.Callback {

		@Override
		public void onDestroyActionMode(ActionMode mode) {
		}

		@Override
		public boolean onCreateActionMode(ActionMode mode,
				com.actionbarsherlock.view.Menu menu) {
			menu.add(R.string.apagar).setIcon(R.drawable.trash)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode,
				com.actionbarsherlock.view.Menu menu) {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode,
				final com.actionbarsherlock.view.MenuItem item) {
			// Toast.makeText(getActivity(),"Got click: " + item + " - " +
			// despesa.getDescricao(), Toast.LENGTH_SHORT).show();

			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

			builder.setTitle(R.string.apagar_movimentacao);
			builder.setMessage(R.string.confirmar_remocao);

			builder.setCancelable(false);
			builder.setPositiveButton(R.string.sim,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							try {
								if (poupanca != null) {
									repositorioPoupanca.excluir(poupanca);
								}

								Toast.makeText(getActivity(),
										"Exclu\u00eddos com sucesso!",
										Toast.LENGTH_SHORT).show();
								mListener.onChange(true);
								changed = true;
								// loadData();

							} catch (SQLException e) {
							}

						}
					});
			builder.setNegativeButton(R.string.nao,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();
						}
					});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();

			mode.finish();
			return true;
		}
	}

	public void setChanged(boolean changed) {
		this.changed = changed;
	}

	public void onAttach(Activity activity) {
	    try {
	    	super.onAttach(activity);
	        this.mListener = (OnChangeListener)activity;

	    }
	    catch (final ClassCastException e) {
	        throw new ClassCastException(activity.toString() + " must implement OnChangeListener");
	    }
	}
}
